package org.example.execute;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.plugin.logging.Log;
import org.example.dto.ColumnDto;
import org.example.service.GenerateCode;
import org.example.utils.HumpUtils;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Properties;

public class Entity implements GenerateCode {

    public static void execute(Log log, String classPath, String entity, String content) {
        String className = HumpUtils.className(StrUtil.format("{}_entity", entity));
        try {
            String path = StrUtil.format("src/main/java/{}/{}.java", classPath.replaceAll("\\.", "/"), className);
            FileUtil.file(path.substring(0, path.lastIndexOf("/"))).mkdirs();
            FileUtil.file(path).createNewFile();
            log.info(FileUtil.file(path).getPath());
            FileWriter writer = new FileWriter(path);
            writer.write(StrUtil.format("package {};\n\n", classPath));
            writer.write(StrUtil.format("import javax.persistence.*;\n"));
            writer.write(StrUtil.format("import lombok.Data;\n\n"));
            writer.write(StrUtil.format("@Data\n"));
            writer.write(StrUtil.format("@Table(name = \"{}\")\n",entity));
            writer.write(String.format(StrUtil.format("public class {} {\n\n%s}", className), content));
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param log
     * @param entity
     * @param columnDtoList
     * @param properties
     */
    @Override
    public void execute(Log log, String entity, List<ColumnDto> columnDtoList, Properties properties) {
        Boolean service = Boolean.parseBoolean(properties.getProperty("generator.entity"));
        if (!service) {
            return;
        }

        StringBuffer buffer = new StringBuffer();
        columnDtoList.stream().forEach(columnDto -> {
            if (!StringUtils.isEmpty(columnDto.getRemark())) {
                buffer.append("\t/**\n");
                buffer.append(StrUtil.format("\t * {}\n", columnDto.getRemark()));
                buffer.append("\t */\n");
            }
            if (columnDto.getField().equals("id")){
                buffer.append("\t@Id\n");
                buffer.append("\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n");
            }
            buffer.append(StrUtil.format("\tprivate {} {};\n\n", getJavaType(columnDto.getType()), HumpUtils.fieldName(columnDto.getField())));
        });
        String path = properties.getProperty("generator.entity.path");
        execute(log, path, entity, buffer.toString());
    }

    public String getJavaType(String type) {
        if (type.contains("int")) {
            return "Long";
        }
        return "String";
    }
}
